package steed.util.system;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import org.redisson.client.RedisConnectionException;

import steed.exception.runtime.MessageRuntimeException;
import steed.util.base.BaseUtil;
import steed.util.base.DevUtil;
import steed.util.base.PropertyUtil;
import steed.util.redis.RedissonUtil;

public class SynchronizedUtil {
	
	/*public static String getKey(String prefix,String key){
		synchronized (prefix) {
			BaseUtil.getLogger().debug("获取{}的同步ID",prefix);
			String prefix2 = "SynchronizedKeyGenerator_"+prefix;
			String data = (String) DataCacheUtil.getData(key, prefix2);
			if (data == null) {
				data = UUID.randomUUID().toString();
			}
			DataCacheUtil.setData(key, prefix2, data, 1000*60*10L);
			return data;
		}
	}*/
	
	/**
	 * 获取lock,分布式也可以用
	 * 
	 * @param prefix 前缀,不同前缀,即使key相同,返回的结果也不一样,防止多个方法获取到的key冲突
	 * @param key 
	 * @return 
	 * 
	 */
	public static Lock getLock(String key,String prefix){
		key = key +"_steedLock_" +prefix;
		if (!PropertyUtil.getBoolean("standAloneMode")) {
			try {
				return RedissonUtil.getRedisson().getLock(key);
			} catch (RedisConnectionException e) {
				if (DevUtil.devMode) {
					BaseUtil.getLogger().error("redis链接失败,分布式锁启用失败,启用单机锁,错误信息:{}",e.getMessage());
				}else {
					throw new RuntimeException("redis链接失败,分布式锁获取失败!",e);
				}
			}
		}
		ReentrantLock data = (ReentrantLock) DataCacheUtil.getData(key, "steed.util.system.SynchronizedKeyGenerator.getLock(String)");
		if (data == null) {
			data = new ReentrantLock();
		}
		DataCacheUtil.setData(key, "steed.util.system.SynchronizedKeyGenerator.getLock(String)", data, 1000*60*10L);
		return data;
	}
	
	public static Lock getLock(String key){
		return getLock(key, "");
	}
}
